//
//  SFUserAcount.swift
//  SFWeiboPro
//
//  Created by happy on 2017/9/14.
//  Copyright © 2017年 happy. All rights reserved.
//

import UIKit

private let accountName: NSString = "userAccount.json"

class SFUserAcount: NSObject {
    
    var access_token: String?
    
    ///过期时间
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    ///过期日期
    var expiresDate: Date?
    
    ///用户ID
    var uid: String?
    
    var isRealName: Bool = false
    
    ///用户名
    var screen_name: String?
    
    ///用户头像
    var avatar_large:String?
    
    
    override var description: String {
        return yy_modelDescription()
    }
    
    
    override init() {
        super.init()
        
        guard let accountPath = accountName.yw_appendDocumentDir(),
        let data = NSData(contentsOfFile: accountPath),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject] else {
            return
        }
        
        //设置账户模型
        yy_modelSet(with: dict ?? [:])
        
        print("账户信息: \(self)")
        
        //判断accesstoken是否过期
        
//        expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
//        
//        print(expiresDate)
        
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("accessToken 已过期")
            
            access_token = nil
            uid = nil
            //删除保存的文件
           try? FileManager.default.removeItem(atPath: accountPath)
        }
    }
    
    /// 保存当前账号
    func saveAccount() {
        
        var dict = (self.yy_modelToJSONObject() as? [String: AnyObject]) ?? [:]
        
        dict.removeValue(forKey: "expires_in")
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let filePath = accountName.yw_appendDocumentDir() else {
            
            return
        }
        
        //保存文件到沙盒
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print(filePath)
        
    }
}
